import AsyncStorage from '@react-native-async-storage/async-storage';
import { ReminderSettings, GeofenceSettings, AppSettings } from '../types/Reminder';

// 存储键名常量
const STORAGE_KEYS = {
  REMINDERS: 'checkin_reminders',
  GEOFENCES: 'checkin_geofences',
  APP_SETTINGS: 'app_settings',
} as const;

// 初始化默认应用设置
const DEFAULT_APP_SETTINGS: AppSettings = {
  theme: 'system',
  notificationSound: 'default',
  vibrationEnabled: true,
  syncAcrossDevices: false,
};

/**
 * 存储服务 - 处理本地数据持久化
 */
export const StorageService = {
  /**
   * 保存提醒设置
   */
  async saveReminder(reminder: ReminderSettings): Promise<void> {
    try {
      const existingReminders = await this.getReminders();
      const updatedReminders = existingReminders.some(r => r.id === reminder.id)
        ? existingReminders.map(r => r.id === reminder.id ? reminder : r)
        : [...existingReminders, reminder];

      await AsyncStorage.setItem(
        STORAGE_KEYS.REMINDERS,
        JSON.stringify(updatedReminders)
      );
    } catch (error) {
      console.error('Failed to save reminder:', error);
      throw error;
    }
  },

  /**
   * 获取所有提醒设置
   */
  async getReminders(): Promise<ReminderSettings[]> {
    try {
      const value = await AsyncStorage.getItem(STORAGE_KEYS.REMINDERS);
      return value ? JSON.parse(value) : [];
    } catch (error) {
      console.error('Failed to get reminders:', error);
      return [];
    }
  },

  /**
   * 删除提醒设置
   */
  async deleteReminder(reminderId: string): Promise<void> {
    try {
      const existingReminders = await this.getReminders();
      const updatedReminders = existingReminders.filter(r => r.id !== reminderId);

      await AsyncStorage.setItem(
        STORAGE_KEYS.REMINDERS,
        JSON.stringify(updatedReminders)
      );
    } catch (error) {
      console.error('Failed to delete reminder:', error);
      throw error;
    }
  },

  /**
   * 保存地理围栏设置
   */
  async saveGeofence(geofence: GeofenceSettings): Promise<void> {
    try {
      const existingGeofences = await this.getGeofences();
      const updatedGeofences = existingGeofences.some(g => g.id === geofence.id)
        ? existingGeofences.map(g => g.id === geofence.id ? geofence : g)
        : [...existingGeofences, geofence];

      await AsyncStorage.setItem(
        STORAGE_KEYS.GEOFENCES,
        JSON.stringify(updatedGeofences)
      );
    } catch (error) {
      console.error('Failed to save geofence:', error);
      throw error;
    }
  },

  /**
   * 获取所有地理围栏设置
   */
  async getGeofences(): Promise<GeofenceSettings[]> {
    try {
      const value = await AsyncStorage.getItem(STORAGE_KEYS.GEOFENCES);
      return value ? JSON.parse(value) : [];
    } catch (error) {
      console.error('Failed to get geofences:', error);
      return [];
    }
  },

  /**
   * 保存应用设置
   */
  async saveAppSettings(settings: Partial<AppSettings>): Promise<void> {
    try {
      const currentSettings = await this.getAppSettings();
      const updatedSettings = { ...currentSettings, ...settings };

      await AsyncStorage.setItem(
        STORAGE_KEYS.APP_SETTINGS,
        JSON.stringify(updatedSettings)
      );
    } catch (error) {
      console.error('Failed to save app settings:', error);
      throw error;
    }
  },

  /**
   * 获取应用设置
   */
  async getAppSettings(): Promise<AppSettings> {
    try {
      const value = await AsyncStorage.getItem(STORAGE_KEYS.APP_SETTINGS);
      return value ? JSON.parse(value) : DEFAULT_APP_SETTINGS;
    } catch (error) {
      console.error('Failed to get app settings:', error);
      return DEFAULT_APP_SETTINGS;
    }
  },

  /**
   * 清除所有存储数据
   */
  async clearAllData(): Promise<void> {
    try {
      await AsyncStorage.multiRemove([
        STORAGE_KEYS.REMINDERS,
        STORAGE_KEYS.GEOFENCES,
        STORAGE_KEYS.APP_SETTINGS,
      ]);
    } catch (error) {
      console.error('Failed to clear data:', error);
      throw error;
    }
  },
};

export default StorageService;